<template>
  <el-drawer
    :model-value="drawerVisible"
    title="添加分类"
    :before-close="handleClose"
    size="50%"
    direction="rtl"
    class="demo-drawer"
  >
    <div class="demo-drawer__content">
      <el-form :model="form" label-width="100px">
        <!-- Parent Category Name -->
        <el-form-item label="父分类名称">
          <el-input v-model="form.categoryParentName" autocomplete="off" />
        </el-form-item>
        <!-- Child Category Name -->
        <el-form-item label="子分类名称">
          <el-input v-model="form.categoryChildName" autocomplete="off" />
        </el-form-item>
        <!-- Category Image -->
        <el-form-item label="分类图片">
          <upload ref="uploadComponent" @upload-success="handleUploadSuccess"></upload>
        </el-form-item>
        <!-- Standards -->
        <el-form-item label="化学成分">
          <el-input v-model="form.chemicalComposition" autocomplete="off" />
        </el-form-item>
        <el-form-item label="内容描述">
          <el-input v-model="form.content" autocomplete="off" />
        </el-form-item>
        <el-form-item label="纯度">
          <el-input v-model="form.purity" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性能">
          <el-input v-model="form.performance" autocomplete="off" />
        </el-form-item>
        <el-form-item label="容量(升:L)">
          <el-input-number v-model="form.capacity" :min="form.capacity" />
        </el-form-item>
        <el-form-item label="长度(厘米:cm)">
          <el-input-number v-model="form.length" :min="form.length" />
        </el-form-item>
        <el-form-item label="直径(厘米:cm)">
          <el-input-number v-model="form.diameter" :min="form.diameter" />
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="submitForm">添加</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import upload from '@/components/upload.vue';
import { addCategory } from '@/api/category';
import { headImgStore } from '@/store/tokenStore';

const props = defineProps({
  drawerVisible: Boolean,
});

const emit = defineEmits(['update:drawerVisible', 'formSubmitted']);

const form = reactive({
  categoryParentName: '',
  categoryChildName: '',
  categoryImg: '',
  chemicalComposition: '',
  content: '',
  purity: '',
  performance: '',
  capacity: 1,
  length: 1,
  diameter: 1,
});

const uploadComponent = ref(null);
const headImg = headImgStore();

const handleUploadSuccess = (url) => {
  form.categoryImg = url;
};

const submitForm = async () => {
  try {
    if (uploadComponent.value) {
      const uploadPromise = new Promise<void>((resolve) => {
        let unwatch:() => void;
        unwatch = watch(
          () => headImg.headImg,
          (newVal) => {
            if (newVal) {
              resolve();
              unwatch();
            }
          },
          { immediate: true }
        );
        uploadComponent.value.manualUpload();
      });

      await uploadPromise;
    }

    const categoryData = {
      ...form,
      categoryImg: headImg.headImg || '',
    };

    await addCategory(categoryData);
    ElMessage.success('分类添加成功');
    emit('formSubmitted');
    emit('update:drawerVisible', false);
    resetForm();
  } catch (error) {
    ElMessage.error('添加失败，请重试');
    console.error(error);
  }
};

const handleClose = (done) => {
  ElMessageBox.confirm('确认退出填写？退出后将清空填写内容', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(() => {
      emit('update:drawerVisible', false);
      resetForm();
    })
    .catch(() => {});
};

const resetForm = () => {
  Object.assign(form, {
    categoryParentName: '',
    categoryChildName: '',
    categoryImg: '',
    chemicalComposition: '',
    content: '',
    purity: '',
    performance: '',
    capacity: 0,
    length: 0,
    diameter: 0,
  });
  headImg.clearHeadImg();
};

const cancelForm = () => {
  emit('update:drawerVisible', false);
  resetForm();
};
</script>

<style scoped>
.demo-drawer__content {
  padding: 20px;
}

.demo-drawer__footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}
</style>
